<template>
    <n-drawer :show="active" :width="width" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="车辆详情" closable>
            <n-spin :show="loading">
                <n-space vertical :size="24" v-if="car.id">
                    <n-card size="small">
                        <n-space vertical :size="24">
                            <n-form label-placement="left" inline :show-feedback="false">
                                <n-form-item label="车联编号">
                                    <b>C{{ car.id }}</b>
                                </n-form-item>
                                <n-form-item label="所属门店">
                                    <b>{{ car.merchant.name }}</b>
                                </n-form-item>
                                <n-form-item label="车型名称">
                                    <b>{{ car.name }}</b>
                                </n-form-item>
                                <n-form-item label="参数">
                                    <n-space size="small">
                                        <b>{{ car.attr.year }}款</b>
                                        <b>{{ car.attr.liter }}</b>
                                        <b>{{ car.attr.seat }}座</b>
                                        <b>{{ car.attr.door }}门</b>
                                        <b>{{ car.attr.color }}</b>
                                        <b>{{ car.attr.gearauto ? '自动挡' : '手动挡' }}</b>
                                        <b>{{ car.attr.mold }}</b>
                                    </n-space>
                                </n-form-item>
                            </n-form>
                            <n-form label-placement="left" inline :show-feedback="false">
                                <n-form-item label="车牌号码">
                                    <b>{{ car.cno }}</b>
                                </n-form-item>
                                <n-form-item label="车架号">
                                    <b>{{ car.vin }}</b>
                                </n-form-item>
                                <n-form-item label="发动机号">
                                    <b>{{ car.eno }}</b>
                                </n-form-item>
                                <n-form-item label="车辆性质">
                                    <n-space size="small">
                                        <b v-if="car.type == 1">门店车辆</b>
                                        <b v-if="car.type == 2">合伙车辆（共{{ car.count }}合伙人）</b>
                                        <b v-if="car.type == 3">挂靠车辆（共{{ car.count }}合伙人）</b>
                                    </n-space>
                                </n-form-item>
                                <n-form-item label="车辆状态">
                                    <n-space size="small">
                                        <b v-if="car.stop">已停租</b>
                                        <b v-if="!car.stop && car.audit.state == 2 && car.idle && car.upper">空闲中</b>
                                        <b v-if="!car.stop && car.audit.state == 2 && !car.idle">租赁中</b>
                                        <b v-if="!car.stop && car.audit.state == 2 && !car.upper">未上架</b>
                                        <b v-if="!car.stop && car.audit.state == 1">未审核</b>
                                        <b v-if="!car.stop && car.audit.state == 3">未通过</b>
                                        <b v-if="!car.stop && car.temp">临时车</b>
                                    </n-space>
                                </n-form-item>
                            </n-form>

                            <n-form label-placement="left" inline :show-feedback="false">
                                <n-form-item label="车辆押金">
                                    <b>{{ (car.price.deposit / 100).toFixed(2) }} 元/单</b>
                                </n-form-item>
                                <n-form-item label="同行价">
                                    <n-space>
                                        <b>{{ (car.price.pdp / 100).toFixed(2) }} 元/日</b>
                                        <b>{{ (car.price.pmp / 100).toFixed(2) }} 元/月</b>
                                    </n-space>
                                </n-form-item>
                                <n-form-item label="终端价">
                                    <b>{{ (car.price.mdp / 100).toFixed(2) }} 元/日</b>
                                </n-form-item>
                                <!-- <n-form-item label="显示价格">
                                    <b>{{ (car.price.disp / 100).toFixed(2) }} 元/日</b>
                                </n-form-item> -->
                            </n-form>
                            <n-form label-placement="left" inline :show-feedback="false">
                                <n-form-item label="开通服务">
                                    <n-space>
                                        <n-button :type="car.service.onsite.flag ? 'primary' : 'tertiary'" size="small">送车上门</n-button>
                                        <n-button :type="car.service.remote.flag ? 'primary' : 'tertiary'" size="small">异地还车</n-button>
                                        <n-button :type="car.service.bins.flag ? 'primary' : 'tertiary'" size="small">基础保险</n-button>
                                        <n-button :type="car.service.dins.flag ? 'primary' : 'tertiary'" size="small">车损保险</n-button>
                                        <n-button :type="car.service.tins.flag ? 'primary' : 'tertiary'" size="small">三者保险</n-button>
                                        <n-button :type="car.service.free.flag ? 'primary' : 'tertiary'" size="small">车损免赔</n-button>
                                        <n-button :type="car.service.night.flag ? 'primary' : 'tertiary'" size="small">夜间服务</n-button>
                                        <n-button :type="car.service.waive.flag ? 'primary' : 'tertiary'" size="small">免押服务</n-button>
                                    </n-space>
                                </n-form-item>
                            </n-form>
                        </n-space>
                    </n-card>

                    <n-image-group show-toolbar-tooltip>
                        
                        <n-grid :cols="4" :x-gap="12" :y-gap="12">
                            <n-gi>
                                <n-card title="车型图片" size="small" :content-style="{ textAlign: 'center' }">
                                    <n-image object-fit="cover" width="240" height="130" :src="car.cover || 'https://cdn.hangzhouyizuke.com/res/app/icons/zjt/imgn.png'" />
                                </n-card>
                            </n-gi>
                            <n-gi>
                                <n-card title="行驶证" size="small" :content-style="{ textAlign: 'center' }">
                                    <n-image object-fit="cover" width="240" height="130" :src="car.vlc.pica" />
                                </n-card>
                            </n-gi>
                            <n-gi>
                                <!-- <n-card title="行驶证副本" size="small" :content-style="{ textAlign: 'center' }">
                                    <n-image object-fit="cover" width="240" height="130" :src="car.vlc.picb" />
                                </n-card> -->
                            </n-gi>
                        </n-grid>
                    </n-image-group>
                    <n-image-group v-if="car.photo && car.photo.length>0" show-toolbar-tooltip>
                        <n-grid :cols="1" :x-gap="12" :y-gap="12">
                            <n-gi>
                                <n-card title="实车照片" size="small" :content-style="{ textAlign: 'left' }">
                                    <template v-if="car.photo && Array.isArray(car.photo)">
                                        <n-image v-for="item in car.photo" object-fit="cover" width="240" height="130" :src="item" />
                                    </template>
                                </n-card>
                            </n-gi>
                        </n-grid>
                    </n-image-group>

                    <n-card size="small">
                        <n-space>
                            <n-button @click="() => (auditActive = true)" v-if="car.audit.state == 1">车辆审核</n-button>
                            <n-button type="info" @click="() => (editActive = true)" v-if="car.audit.state == 2">车型修改</n-button>
                            <n-button disabled @click="() => (formActive = true)" v-if="car.audit.state == 2">增值服务</n-button>
                            <n-button type="warning" @click="() => (priceActive = true)" v-if="car.audit.state == 2">价格设置</n-button>
                            <n-button @click="() => (settleActive = true)" v-if="car.audit.state == 2">分润设置</n-button>
                            <n-button @click="() => doUpper(car, true)" v-if="car.audit.state == 2 && !car.upper">车辆上架</n-button>
                            <n-button type="error" @click="() => doUpper(car, false)" v-if="car.audit.state == 2 && car.upper">车辆下架</n-button>
                            <n-button @click="() => doRecommend(car, true)" v-if="car.audit.state == 2 && !car.rmd">设为推荐</n-button>
                            <n-button @click="() => doRecommend(car, false)" v-if="car.audit.state == 2 && car.rmd">取消推荐</n-button>
                        </n-space>
                    </n-card>

                    <n-grid :cols="4" :x-gap="12" :y-gap="12">
                        <n-gi>
                            <n-card title="停租设置" size="small">
                                <n-form label-placement="left" :show-feedback="false" v-if="car.stops.length > 0">
                                    <n-form-item v-for="s in car.stops">
                                        <n-space>
                                            <b>{{ s.begin }}</b>
                                            至
                                            <b>{{ s.close }}</b>
                                        </n-space>
                                    </n-form-item>
                                </n-form>
                                <n-empty description="未配置停租" v-else></n-empty>
                            </n-card>
                        </n-gi>
                        <n-gi>
                            <n-card title="最近违章" size="small">
                                <!-- <template #header-extra>
                                    <n-button strong secondary size="tiny">更多</n-button>
                                </template> -->
                                <n-form label-placement="left" :show-feedback="false" v-if="car.vos.length > 0">
                                    <n-form-item label="违章地点">
                                        <b>{{ car.vos[0].addr }}</b>
                                    </n-form-item>
                                    <n-form-item label="违章时间">
                                        <b>{{ car.vos[0].time }}</b>
                                    </n-form-item>
                                    <n-form-item label="违章内容">
                                        <b>{{ car.vos[0].info }}</b>
                                    </n-form-item>
                                    <n-form-item label="违章代码">
                                        <b>{{ car.vos[0].code }}</b>
                                    </n-form-item>
                                    <n-form-item label="违章处罚">
                                        扣
                                        <b>{{ car.vos[0].score }}</b>
                                        分，罚款
                                        <b>{{ car.vos[0].fine }}</b>
                                        元
                                    </n-form-item>
                                </n-form>
                                <n-empty description="暂无违章信息" v-else></n-empty>
                            </n-card>
                        </n-gi>
                        <n-gi>
                            <n-card title="最近纠纷" size="small">
                                <!-- <template #header-extra>
                                    <n-button strong secondary size="tiny">更多</n-button>
                                </template> -->
                                <n-form label-placement="left" :show-feedback="false" v-if="car.dispute.length > 0">
                                    <n-form-item label="发生时间">
                                        <b>{{ car.dispute[0].time }}</b>
                                    </n-form-item>
                                    <n-form-item label="纠纷内容">
                                        <b>{{ car.dispute[0].info }}</b>
                                    </n-form-item>
                                    <n-form-item label="处理状态">
                                        <b>{{ car.dispute[0].state }}</b>
                                    </n-form-item>
                                    <n-form-item label="客户信息">
                                        <n-space>
                                            <b>{{ car.dispute[0].customer.phone }}</b>
                                            {{ car.dispute[0].customer.name }}
                                        </n-space>
                                    </n-form-item>
                                </n-form>
                                <n-empty description="暂无纠纷信息" v-else></n-empty>
                            </n-card>
                        </n-gi>
                        <n-gi>
                            <n-card title="最近收入" size="small">
                                <!-- <template #header-extra>
                                    <n-button strong secondary size="tiny">更多</n-button>
                                </template> -->
                                <n-form label-placement="left" :show-feedback="false" v-if="car.income.length > 0">
                                    <n-form-item label="订单编号">
                                        <b>D{{ car.income[0].id }}</b>
                                    </n-form-item>
                                    <n-form-item label="订单时间">
                                        <b>{{ car.income[0].time }}</b>
                                    </n-form-item>
                                    <n-form-item label="订单金额">
                                        <b>{{ (car.income[0].total / 100).toFixed(2) }}</b>
                                    </n-form-item>
                                    <n-form-item label="平台收入">
                                        <b>{{ (car.income[0].plat / 100).toFixed(2) }}</b>
                                    </n-form-item>
                                    <n-form-item label="客户信息">
                                        <n-space>
                                            <b>{{ car.income[0].customer.phone }}</b>
                                            {{ car.income[0].customer.name }}
                                        </n-space>
                                    </n-form-item>
                                </n-form>
                                <n-empty description="暂无订单收入" v-else></n-empty>
                            </n-card>
                        </n-gi>
                    </n-grid>

                    <n-card size="small" title="最近订单">
                        <template #header-extra>
                            <n-button
                                strong
                                secondary
                                size="tiny"
                                @click="
                                    () => {
                                        ordersActive = true
                                    }
                                "
                            >
                                更多
                            </n-button>
                        </template>

                        <n-table :single-line="false">
                            <thead>
                                <tr>
                                    <th>订单ID</th>
                                    <th>下单时间</th>
                                    <th>完成/取消时间</th>
                                    <th>订单状态</th>
                                    <th>客户信息</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="order in orders">
                                    <td>
                                        <n-button
                                            @click="
                                                () => {
                                                    oitem = order
                                                    orderActive = true
                                                }
                                            "
                                        >
                                            D{{ order.id }}
                                        </n-button>
                                    </td>
                                    <td>{{ order.times.create }}</td>
                                    <td>{{ order.times.finish || order.times.cancel }}</td>
                                    <td>
                                        <n-tag :bordered="false" size="small" type="error" v-if="order.state == 1">等待支付</n-tag>
                                        <n-tag :bordered="false" size="small" type="warning" v-if="order.state == 2">等待服务</n-tag>
                                        <n-tag :bordered="false" size="small" type="success" v-if="order.state == 3">租赁中</n-tag>
                                        <n-tag :bordered="false" size="small" type="info" v-if="order.state == 4">已完成交车</n-tag>
                                        <n-tag :bordered="false" size="small" v-if="order.state == 9">订单取消</n-tag>
                                    </td>
                                    <td>
                                        <n-text code>{{ order.customer.phone }}</n-text>
                                        {{ order.customer.name }}
                                    </td>
                                </tr>
                            </tbody>
                        </n-table>
                        <n-empty description="暂无订单信息" v-if="orders.length == 0"></n-empty>
                    </n-card>
                </n-space>
            </n-spin>

            <template #footer>
                <n-space justify="space-between" :style="{ width: '100%' }">
                    <n-space></n-space>
                    <n-button @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>

        <Audit :item="car" v-model:show="auditActive" v-if="auditActive" @refresh="execLoad"></Audit>
        <Edit :item="car" v-model:show="editActive" v-if="editActive" @refresh="execLoad"></Edit>
        <Price :item="car" v-model:show="priceActive" v-if="priceActive" @refresh="execLoad"></Price>
        <Settle :item="car" v-model:show="settleActive" v-if="settleActive" @refresh="execLoad"></Settle>
        <Orders :item="car" v-model:show="ordersActive" v-if="ordersActive"></Orders>
        <Order :item="oitem" v-model:show="orderActive" v-if="orderActive"></Order>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { CloseRound } from '@vicons/material'
import { useStore } from '@/store'
import { Http } from '@/libs'

import Audit from './Audit.vue'
import Edit from './Edit.vue'
import Price from './Price.vue'
import Settle from './Settle.vue'
import Orders from './Orders.vue'
import Order from '../order/View.vue'

import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn' // 导入本地化语言
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.locale('zh-cn')
dayjs.extend(customParseFormat)

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.8, 1200))
const loading = computed(() => store.state.loading.flag)

const { $notification: notification } = window
const { $dialog: dialog } = window

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        required: true,
    },
})

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})
const car = ref<any>({})
const execLoad = () => {
    if (car.value.id) {
        emit('refresh', {})
    }
    Http.post('/ops/biz/car/detail', { id: prop.item.id }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        console.log('detail', resp.data)
        car.value = resp.data
        execLoadOrder()
    })
}
const orders = ref<any>([])

const execLoadOrder = () => {
    Http.post('/ops/biz/order/list', {
        query: {
            begin: dayjs().subtract(1, 'year').format('YYYY-MM-DD'),
            close: dayjs().format('YYYY-MM-DD'),
            mchid: '',
            carid: car.value.id,
            orderid: '',
            rentid: '',
            area: '',
            name: '',
            mob: '',
            state: 0,
        },
        pager: {
            page: 1,
            size: 5,
            time: new Date().getTime(),
        },
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        orders.value = resp.data.items
    })
}

onMounted(() => {
    execLoad()
})

const formActive = ref<boolean>(false)
const auditActive = ref<boolean>(false)
const editActive = ref<boolean>(false)
const priceActive = ref<boolean>(false)
const settleActive = ref<boolean>(false)
const ordersActive = ref<boolean>(false)
const orderActive = ref<boolean>(false)
const oitem = ref<any>({})
const doUpper = (row: any, upper: boolean) => {
    if (upper && !car.value.cover) {
        notification.error({
            duration: 1500,
            title: '尚未设置车型图片，无法上架',
            content: `请在 [车型修改] 中设置车型图片`,
        })
        return
    }
    dialog.info({
        title: `提示?`,
        content: `是否 ${upper ? '上架' : '下架'} 车辆 [ ${row.cno} - ${row.name} ]?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            execUpper(row.id, upper)
        },
    })
}

const execUpper = (id: string, upper: boolean) => {
    Http.post('/ops/biz/car/upper/set', {
        id: id,
        upper: upper,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        emit('refresh', {})

        notification.success({
            duration: 1500,
            title: '操作成功',
            content: `您已成功 ${upper ? '上架' : '下架'} 车辆`,
        })
    })
}

const doRecommend = (row: any, rmd: boolean) => {
    dialog.info({
        title: `提示?`,
        content: `是否 ${rmd ? '设为推荐' : '取消推荐'} 车辆 [ ${row.cno} - ${row.name} ]?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            execRecommend(row.id, rmd)
        },
    })
}

const execRecommend = (id: string, rmd: boolean) => {
    Http.post('/ops/biz/car/rmd/set', {
        id: id,
        rmd: rmd,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        emit('refresh', {})
        notification.success({
            duration: 1500,
            title: '操作成功',
            content: `您已成功 ${rmd ? '设为推荐' : '取消推荐'} 车辆`,
        })
    })
}
</script>
